package com.tust.app.controller;



import com.github.pagehelper.PageInfo;
import com.tust.app.domain.Answer;
import com.tust.app.domain.Topic;
import com.tust.app.service.AnswerService;
import com.tust.app.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AnswerController {

    @Autowired
    private AnswerService answerService;
    @Autowired
    private TopicService topicService;

    @GetMapping("/selectAllAnswer")
    public String selectAllAnswer(@RequestParam(value = "pn", defaultValue = "1") int pageNum, Model model) {
        PageInfo answerLists = answerService.getAllAnswers(pageNum);
        model.addAttribute("answerLists", answerLists);
        return "admin/bbs/allAnswers";
    }

    @GetMapping("/updateAnswerState")
    public String updateAnswerState(@RequestParam("id") int id) {
        answerService.updateAnswerState(id);
        return "redirect:/selectAllAnswer";
    }

    @GetMapping("/deleteAnswer")
    public String deleteAnswer(@RequestParam("id") int id) {
        answerService.deleteAnswer(id);
        return "redirect:/selectAllAnswer";
    }

    @PostMapping("/addAnswer")
    public String addAnswer(@RequestParam("answeruser") String answerUser,
                            @RequestParam("topicId") int topicId,
                            @RequestParam("content") String content,Model model) {

        Answer answer = new Answer();
        answer.setAnsweruser(answerUser);
        answer.setContent(content);
        answer.setTopicId(topicId);
        answer.setPubtime2(String.valueOf(LocalDate.now()));
        answerService.addAnswer(answer);
        // 重定向到另一个页面
        Topic topic = topicService.selectTopicAnswerById(topicId);
        model.addAttribute("list", topic);
        return "redirect:/selectTopicAnswerById?id="+topicId;
    }
}
